package leetcode.code0813;

import leetcode.IDebug;
import leetcode.helper.H;

//执行用时：2564 ms, 在所有 Java 提交中击败了5.13%的用户
//
//内存消耗：50.7 MB, 在所有 Java 提交中击败了5.13%的用户
//
//通过测试用例：51 / 51
public class Solution implements IDebug {
	int[] nums;
	int[] sums;

	public double largestSumOfAverages(int[] nums, int k) {
		this.nums = nums;
		int len = nums.length;
		this.sums = new int[len + 1];
		for (int i = 1; i <= len; i++) {
			sums[i] = sums[i - 1] + nums[i - 1];
		}
		Double[][][] dp = new Double[len][len][k + 1];
		return this.check(0, len - 1, k, dp);
	}

	private double check(int L, int R, int K, Double[][][] dp) {
		if (L == R) {
			return this.nums[L];
		}
		if (K == 1) {
			return 1d * (this.sums[R + 1] - this.sums[L]) / (R - L + 1);
		}
		if (dp[L][R][K] != null) {
			return dp[L][R][K];
		}
		double ans = 0;
		for (int i = L; i < R; i++) {
			for (int k = 1; k <= Math.min(i - L + 1, K - 1); k++) {
				int rest = K - k;
				if (R - i >= rest) {
					ans = Math.max(ans, this.check(L, i, k, dp) + this.check(i + 1, R, rest, dp));
				}
			}
		}
		dp[L][R][K] = ans;
		return ans;
	}

	@Override
	public void debug4() {
		H.compare(20, this.largestSumOfAverages(H.str2array3("[9,1,2,3,9]"), 3));
	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
